<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Member_Order_listener extends ORM
{
    public static function detect($ordersn)
    {
        try {
            $query = DB::select()->from('member_order')->where('ordersn', '=', $ordersn);
            $sql   = $query->compile();
            $order = $query->execute()->current();
            if (!$order) {
                throw new Exception("订单不存在：sql:{$sql}");
            }
            $sql = <<<sql
        SELECT
            *
        FROM
            sline_member_order_listener
        WHERE
            (webid IS NULL OR webid = {$order['webid']})
        AND (typeid IS NULL OR typeid = {$order['typeid']})
        AND (
            supplierlist IS NULL
            OR supplierlist = ''
            OR supplierlist = '{$order['supplierlist']}'
        )
        AND (
            distributor IS NULL
            OR distributor = ''
            OR distributor = '{$order['distributor']}'
        )
        AND (
            productautoid IS NULL
            OR productautoid = {$order['productautoid']}
        )
        AND (suitid IS NULL OR suitid = {$order['suitid']})
        AND (
            order_status IS NULL
            OR order_status = {$order['status']}
        )
        AND isenabled = 1
sql;

            $listener_list = DB::query(Kohana_Database::SELECT, $sql)->execute()->as_array();
            if (count($listener_list) <= 0) {
                self::write_order_listener_log($ordersn, "query_order_listener", "no order listener,sql:{$sql}");
                return true;
            }

            $host = DB::select()->from('weblist')->where('webid', '=', 0)->execute()->current();
            if ($host && !empty($host['weburl'])) {
                $host = $host['weburl'];
            } else {
                $host = St_Functions::get_http_prefix() . "{$_SERVER['HTTP_HOST']}";
            }

            foreach ($listener_list as $listener) {
                self::curl_request($listener, $host, $ordersn);
            }
        } catch (Exception $e) {
            self::write_order_listener_log($ordersn, "execution_error", $e->getMessage());
        }

        return true;
    }

    public static function curl_request($listener, $host, $order_sn)
    {
        $execurl = $listener['execute_url'];
        if (stristr($execurl, '?') === false) {
            $execurl = $execurl . "?ordersn={$order_sn}";
        } else {
            $execurl = $execurl . "&ordersn={$order_sn}";
        }

        $execurl = trim($execurl);
        if (stripos($execurl, "http://") !== 0 && stripos($execurl, "https://") !== 0) {
            $execurl = "{$host}/{$execurl}";
        }

        $execresult_text = self::request($execurl);
        self::write_order_listener_log($execurl, "call_order_listener", $execresult_text);

        $execresult = json_decode($execresult_text, true);
        $status     = $execresult['status'];
        $retry      = 0;

        while (!$status && $retry < 3) {
            $execresult_text = self::request($execurl);
            self::write_order_listener_log($execurl, "call_order_listener_{$retry}", $execresult_text);

            $execresult = json_decode($execresult_text, true);
            $status     = $execresult['status'];
            $retry++;
        }
    }

    private static function write_order_listener_log($ordersn, $action, $result)
    {
        $payLogDir = BASEPATH . '/data/order_listener_log/';
        if (!file_exists($payLogDir)) {
            mkdir($payLogDir, 0777, true);
        }
        //日志文件
        $file = $payLogDir . date('ymd') . '.txt';
        $now  = date('YmdHis');

        $data = "=========================" . PHP_EOL;
        $data .= "ordersn:{$ordersn} {$now}" . PHP_EOL;
        $data .= "action:{$action}" . PHP_EOL;
        $data .= "result:{$result}" . PHP_EOL;

        file_put_contents($file, $data, FILE_APPEND);
    }

    private static function request($url)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

        $return = curl_exec($ch);
        curl_close($ch);

        return $return;
    }
}